package com.huluobo.mvvm.view;

import android.media.metrics.Event;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

import com.huluobo.mvvm.baen.UserBeanResult;
import com.huluobo.mvvm.event.CustomEvent;
import com.huluobo.mvvm.model.BaseRepo;
import com.huluobo.mvvm.viewmodel.BaseViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by LC on 2023/9/14.
 */
public abstract class BaseMVVMActivity<VDB extends ViewDataBinding, VM extends BaseViewModel> extends AppCompatActivity {
    protected VDB dataBinding;
    protected VM viewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //1.绑定视图
        dataBinding = DataBindingUtil.setContentView(this, getLayoutId());
        //2.绑定ViewModel
        viewModel = new ViewModelProvider(this).get(getViewModel());
        //3.初始化控件
        initView();
        //4.初始化数据
        initData();
        //5.注册EventBus
        EventBus.getDefault().register(this);
    }

    //在主线程当中接收EventBus的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(CustomEvent event) {
        //校验事件是否合法
        if (event == null || TextUtils.isEmpty(event.getTarget())) return;

        //目标页校验,对比事件中的类名,是否等于当前类的名字
        if (event.getTarget().equals(getClass().getSimpleName())) {
            //处理事件
            handEvent(event);
        }
    }

    public void handEvent(CustomEvent event) {
        //TODO 让子类去处理,可以重写也可以不写
    }

    protected abstract void initData();

    protected abstract void initView();

    protected abstract Class<VM> getViewModel();

    protected abstract int getLayoutId();

}
